<template>
  <div>
    <!-- 搜索 -->
      <search/>
    <!-- 搜索 -->
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <div class="wrap">
        <!-- bannar -->
        <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
          <van-swipe-item v-for="banner in banners" :key="banner.id">
            <img :src="banner.picUrl" alt="">
          </van-swipe-item>
        </van-swipe>
        <!-- bannar -->
        <!-- 宫格导航 -->
        <van-grid>
          <van-grid-item :to="{ path:'/itemLists',  query: { cate_id: cate.id, cate_name: cate.name } }" v-for="cate in cates" :key="cate.id" :icon="cate.icon" :text="cate.name" />
        </van-grid>
        <!-- 宫格导航 -->
        <!-- 商品展示 -->
        <van-list v-model="loading" :finished="finished" :offset="offset" finished-text="没有更多了" @load="onLoad" v-if="items.length" >
          <floor
            @clickItem="enterDetail"
            :items="items" />
        </van-list>
        <!-- 商品展示 -->
      </div>
    </van-pull-refresh>
    <!-- 底部导航 -->
    <my-tabbar />
    <!-- 底部导航 -->
  </div>
</template>

<script>
import MyTabbar from '@components/MyTabbar'
import Search from './components/Search'
import Floor from './components/Floor'
import { fetchBanner, fetchCate, fetchItems } from '@api'

export default {
  data () {
    return {
      banners: [],
      cates: [],
      items: [],
      page: 1, // 默认获取第一页数据
      pageSize: 5, // 一页多少条
      loading: false,
      finished: false,
      offset: 20,
      isLoading: false
    };
  },
  created () {
    this.fetchBanner()
    this.fetchCate()
    this.fetchItems()
  },
  methods: {
    enterDetail (itemId) {
      // 进入详情页
      this.$router.push(`/detail/${itemId}`)
    },
    onRefresh () {
      // 下拉刷新了
      this.items = []
      this.page = 1
      this.finished = false
      this.fetchItems()
    },
    onLoad () {
      this.page++
      this.fetchItems()
    },
    fetchItems () {
      fetchItems({
        categoryId: 211052,
        page: this.page,
        pageSize: this.pageSize
      }).then(res => {
        this.isLoading = false
        if (res.data.code === 700) {
          this.loading = false
          this.finished = true
        }
        if (res.data.code === 0) {
          this.items = [...this.items, ...res.data.data]
          this.loading = false
        }
      })
    },
    fetchBanner () {
      fetchBanner().then(res => {
        if(res.data.code === 0) {
          this.banners = res.data.data
        }
      })
    },
    fetchCate () {
      fetchCate().then(res => {
        console.log( res )
        if (res.data.code === 0) {
          this.cates = res.data.data
        }
      })
    }
  },
  components: {
    MyTabbar,
    Search,
    Floor
  }
}
</script>
<style lang="scss" scoped>
body{
  background: rgb(243,245,247);
}
.wrap{
  margin: 50px 0;
  background: rgb(243,245,247);
  .my-swipe img{
    width: 100%;
  }
}
</style>
